/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TelasPedido;

import DAO.ItemDAO;
import DAO.PedidoDAO;
import Pojo.Item;
import Pojo.Pedido;
import View.MenuPedido;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 *
 * @author DanielPC
 */
public class TelaListarItensDoPedido extends javax.swing.JFrame {
    MenuPedido menuPedido;
    Pedido pedido1;
    PedidoDAO pedidoDao;
    ItemDAO itemDao1;
    int verificaNota;

    public TelaListarItensDoPedido(PedidoDAO pedidoDao, Pedido pedido,ItemDAO itemDao,int verificaNota) {
        this.pedido1 = pedido;
        this.pedidoDao = pedidoDao;
        this.itemDao1 = itemDao;
        this.verificaNota = verificaNota;
        initComponents();
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        HashMap<Item, Integer> hashItens;
        hashItens = pedido.getHash();
        Set mapSet = (Set) hashItens.entrySet();
        Iterator mapIterator = mapSet.iterator();
        for (Map.Entry<Item, Integer> entry : hashItens.entrySet()) {
            Map.Entry mapEntry = (Map.Entry) mapIterator.next();
            Item aux = (Item) mapEntry.getKey();
            String[] linha = new String[]{Integer.toString(aux.getCodigo()),
                aux.getNome(), String.valueOf(mapEntry.getValue()),
                Float.toString(aux.CalcularPreco())};
            modelo.addRow(linha);
        }
        jTable1.setModel(modelo);
        
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lista de itens");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nome", "Quantidade", "Preço"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setRequestFocusEnabled(false);
        jTable1.setSurrendersFocusOnKeystroke(true);
        jTable1.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                jTable1InputMethodTextChanged(evt);
            }
        });
        jTable1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jTable1PropertyChange(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Remover Item");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Atualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Lista de Itens do pedido");

        jButton3.setText("Alterar Quantidade");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(196, 196, 196)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addGap(47, 47, 47)
                                .addComponent(jButton3)
                                .addGap(46, 46, 46)
                                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addGap(33, 33, 33))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if(verificaNota ==1){
            jButton2.setEnabled(false);
        }else{
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        HashMap<Item, Integer> hashItens;
        hashItens = pedido1.getHash();
        Item itemAux;
        Set mapSet = (Set) hashItens.entrySet();
        Iterator mapIterator = mapSet.iterator();
        int linha=0;
        if(modelo.getRowCount()>0){
         do{
            Map.Entry mapEntry = (Map.Entry) mapIterator.next();
            itemAux = (Item)mapEntry.getKey();
            if((jTable1.getValueAt(linha, 2)==null)){
                JOptionPane.showMessageDialog(this, "Quantidade não Alterada, Faltam Valores."
                        + "(Precione 'Enter' após a inserção do valor)");
            }
            else if(mapEntry.getValue() != jTable1.getValueAt(linha, 2)&& Integer.valueOf((String)jTable1.getValueAt(linha, 2))<=itemAux.getQuantidade()){
                mapEntry.setValue((String)jTable1.getValueAt(linha, 2));
                pedidoDao.escreverArquivo();
                this.dispose();
            }
            else if(mapEntry.getValue() == jTable1.getValueAt(linha, 2)){
                this.dispose();
            }
            else{
                JOptionPane.showMessageDialog(this, itemAux.getNome()+" Execeu a quantidade limite do estoque!");
            }
            linha++;
         }while(mapIterator.hasNext());
        }
        else{
            this.dispose();
        }
      }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        TableModel modelo1 = (TableModel) jTable1.getModel();
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        int linha = jTable1.getSelectedRow();
        if (linha < 0 || linha > modelo.getRowCount()) {
            JOptionPane.showMessageDialog(this, "Clique no item");
        } else {
            modelo.isCellEditable(linha, 2);
            jTable1.editCellAt(linha, 2);
        }
        HashMap<Item, Integer> hashItens;
        hashItens = pedido1.getHash();
        Set mapSet = (Set) hashItens.entrySet();
        Iterator mapIterator = mapSet.iterator();
        Map.Entry mapEntry = (Map.Entry) mapIterator.next();
        Item aux = (Item) mapEntry.getKey();
        jTable1.setModel(modelo);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTable1InputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_jTable1InputMethodTextChanged
        // TODO add your handling code here
    }//GEN-LAST:event_jTable1InputMethodTextChanged

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
       // TODO add your handling code here
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jTable1PropertyChange
        // TODO add your handling code here
    }//GEN-LAST:event_jTable1PropertyChange

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_formKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if(verificaNota==1){
            jButton1.setEnabled(false);
        }else{
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            Item itemAux;
            int linha = jTable1.getSelectedRow();
            if (linha < 0 || linha > modelo.getRowCount()) {
                JOptionPane.showMessageDialog(this, "Clique no item");
            }else{
                String nome = (String)jTable1.getValueAt(linha, 1);
                itemAux = itemDao1.buscaItemNome(nome);
                pedido1.getHash().remove(itemAux);
                JOptionPane.showMessageDialog(this, "Removido com sucesso!");
                modelo.removeRow(linha);
                pedidoDao.escreverArquivo();
            }
            if(modelo.getRowCount()==0)
                 this.dispose();
        }
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
